<?php 
App::uses('AppController', 'Controller');

class StallsPostingController extends AppController {
	
	var $components = array('Link','Files','Images','Strings');
	var $helpers = array('Paginator','Html');
	public $user = "";
	public function beforeFilter(){
		
		$this->user = parent::checkMemberLogin();
		$this->set("user",$this->user);
		parent::leftMember();
	}
	/**
	 * @author QuocTran
	 * thêm sản phâm trong gian hàng
	 */
	public function index() {
		$this->layout = 'layoutNoMenuLeft';
		$this->set("title_for_layout","Thêm sản phẩm");
		
		$this->loadModel('Image');
		$this->loadModel('ShopCategory');
		$this->loadModel('Product');
		$this->loadModel('Shop');
		
		$shop = $this -> Shop -> findShopByCreatedId($this->user['id']);
		if(empty($shop)){
			$this->redirect('/quan-ly-user');
		}
		$this->set('shop',$shop);
		$this->set('rootCategories',$this -> ShopCategory->findShopCategoryByShopId($shop['Shop']['id'], $this->user['id']));
		
		if ($this -> request -> is('post')) {
			$new = $this -> data;
			$new['product_name'] = $this->Strings->replaceHTMLTag($new['product_name']);
			$new['short_url'] = $this->Link->getShortLink($new['product_name']);
			$new['image_icon'] = $this->Images->createIconImage($new['img'], ICON_WIDTH, ICON_HEIGHT);
			$new['price'] = str_replace(",", "", $new['price']);
			$new['manufacturer'] = $this->Strings->replaceHTMLTag($new['manufacturer']);
			$new['model'] = $this->Strings->replaceHTMLTag($new['model']);
			$new['content'] = $this->Strings->replaceHTMLTag($new['content']);
			if(isset($new['option1'])){
				if($new['option1'] == 0){
					$new['option'] =$new['option2'];
				}else{
					$new['option'] =$new['option1'];
				}
			}
			
			$new['shop_id'] = $shop['Shop']['id'];
			$new['created_by'] = $this->user['id'];//lấy id của user login
			$new['created_at'] = date("Y-m-d H:i:s");
			$new['updated_by'] = $this->user['id'];//lấy id của user login
			$new['updated_at'] = date("Y-m-d H:i:s");
			
			
			if ($this -> Product -> save($new)){
				$idProduct= $this->Product->id;
				$imgList = $new['img'];
				$imgNew= array();
				foreach ($imgList as $i) {
					if(!empty($i)){
						$img['url']=$i;
						$img['product_id'] = $idProduct;
						$img['deleted'] = 0;
						$img['created_by'] = $this->user['id'];//lấy id của user login
						$img['created_at'] = date("Y-m-d H:i:s");
						$img['updated_by'] = $this->user['id'];//lấy id của user login
						$img['updated_at'] = date("Y-m-d H:i:s");
						array_push($imgNew, $img);
					}
				}
				if(count($imgNew)>0){
					$this->Image->saveMany($imgNew);
				}
				$this->redirect('/quan-ly-user/gian-hang/san-pham');
			}
		}
		
	}
	/**
	 * @author QuocTran
	 * chỉnh sửa sản phẩm trong gian hàng
	 */
	public function edit($id) {
		$this->layout = 'layoutNoMenuLeft';
		$this->set("title_for_layout","Chỉnh sửa sản phẩm");
		
		$this->loadModel('Image');
		$this->loadModel('ShopCategory');
		$this->loadModel('Product');
		$this->loadModel('Shop');
		
		$shop = $this -> Shop -> findShopByCreatedId($this->user['id']);
		
		$this->set('rootCategories',$this -> ShopCategory->findShopCategoryByShopId($shop['Shop']['id'], $this->user['id']));
		
		$product = $this->Product->findByConditions($id, $shop['Shop']['id'], $this->user['id']);
		$this->set('product',$product['Product']);
		
		$this->set("img",$this->Image->findAllByProductId($id));
		
		
		if ($this -> request -> is('post')) {
			$new = $this -> data;
			$new['product_id'] = $id;
			$new['product_name'] = $this->Strings->replaceHTMLTag($new['product_name']);
			if(isset($new['option1'])){
				if($new['option1'] == 0){
					$new['option'] =$new['option2'];
				}else{
					$new['option'] =$new['option1'];
				}
			}
			
			$new['price'] = str_replace(",", "", $new['price']);
			$new['manufacturer'] = $this->Strings->replaceHTMLTag($new['manufacturer']);
			$new['model'] = $this->Strings->replaceHTMLTag($new['model']);
			$new['content'] = $this->Strings->replaceHTMLTag($new['content']);
			$new['shop_id'] = $shop['Shop']['id'];
			$new['updated_at'] = date("Y-m-d H:i:s");
			
			if ($this -> Product -> save($new)){
				$idProduct= $id;
				$imgList = $new['img'];
				
				$imgNew= array();
				foreach ($imgList as $i) {
					$img = array();
					if(!empty($i['id']) || !empty($i['url']) ){
						
						$img['product_id'] = $idProduct;
						$img['deleted'] = 0;
						$img['created_by'] = $this->user['id'];//lấy id của user login
						$img['created_at'] = date("Y-m-d H:i:s");
						$img['updated_by'] = $this->user['id'];//lấy id của user login
						$img['updated_at'] = date("Y-m-d H:i:s");
						if(isset($i['id'])){
							$img['id']=$i['id'];
						}
						if(!empty($i['url'])){
							$img['url']=$i['url'];
						}
						if(!empty($i['id']) && empty($i['url'])){
							$img['deleted'] = 1;
						}
							
						array_push($imgNew, $img);
					}
				}
				if(count($imgNew)>0){
					
					$this->Image->saveMany($imgNew);
				}
				$this->redirect('/quan-ly-user/gian-hang/san-pham');
			}
		}
		
	}
	/**
	 * QuocTran
	 * ajax upload image
	 */
	public function uploadImage(){
		if ($_SERVER['REQUEST_METHOD'] != 'POST' || empty($_FILES['image']) ) {
			echo json_encode(array('success'=>'2','path'=>"Invalid file!"));
			exit();
		}
		if ($this->Files ->isValidFileType($_FILES['image']['name'])){
			//upload file
			$path = $this->Files->uploadFile(UPLOAD_IMG_PRODUCT, $_FILES['image']['tmp_name'], ROOT_IMG_PRODUCT, $_FILES['image']['name']);
			//resize
			//$this->Image->resizeImage(WWW_ROOT.$path, IMAGE_WIDTH, IMAGE_HEIGHT);
			echo json_encode(array('success'=>'1','path'=>$path));
		}else{
			echo json_encode(array('success'=>'2','path'=>""));
		}
		exit();
	}
	/**
	 * QuocTran
	 * delete image
	 */
	public function deleteImage(){
		if ($this -> request -> is('post')) {
			$path = WWW_ROOT.substr($_POST['src'],1);
			$this->Files -> deleteFile($path);
			echo json_encode(array('success'=>true));
		}else{
			echo json_encode(array('success'=>false));
		}
		exit();
	}
	public function delete($id){
		$this->loadModel('Product');
		$this -> loadModel('Image');
		
		$pr = $this->Product->findById($id);
		if(!empty($pr)){
		   $images = $this->Image->findAllByProductId($id);
		   foreach ($images as $i) {
				$path = WWW_ROOT.$i['Image']['url'];
				$this->Files -> deleteFile($path);
			}
		    $this->Image->deleteAll(array('Image.product_id' => $id), false);
			$path = WWW_ROOT.$pr['Product']['image_icon'];
			$this->Files -> deleteFile($path);
			$this->Product->delete($id, false);
		}
		$this->redirect('/quan-ly-user/gian-hang/san-pham');
	} 
	/**
	 * list all product
	 */
	public function listProduct(){
		$this -> layout = 'layoutMember';
		$this->loadModel('Shop');
		$this->set('title_for_layout','Sản phẩm');
		
		$this->loadModel('Product');
		$this->loadModel('Shop');
		
		$shop = $this -> Shop -> findShopByCreatedId($this->user['id']);
		//$products = $this->Product->findAllLastestById($shop['Shop']['id']);
		
		//$this->set("data",$products);
		
		$conditions = array('shop_id' => $shop['Shop']['id']);
		$this->paginate = array(
                                'limit' => ITEM_PER_PAGE,
                                'order' => array('product_id' => 'desc'),
                             );
        $data = $this->paginate("Product",$conditions);
        $this->set("data",$data);
	}
}
?>